package cn.itrip.auth.controller;

import cn.itrip.auth.exception.DatabaseException;
import cn.itrip.auth.exception.LoginException;
import cn.itrip.auth.service.TokenService;
import cn.itrip.auth.service.UserService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: jxm
 * @Description:
 * @Date: 2020/3/12 15:41
 * @Version: 1.0
 */
@Controller
@RequestMapping("/api")
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;

    /**
     * 登录
     * @param userCode
     * @param userPassword
     * @param request
     * @return
     */
    @RequestMapping(value="/doLogin",method = RequestMethod.POST,produces = "application/json")
    @ResponseBody
    public Dto doLogin(@RequestParam String userCode, @RequestParam String userPassword,
                       HttpServletRequest request){
        ItripUser user = null;
        try {
            if((user = userService.checkLogin(userCode,userPassword)) == null){
                //用户名密码错误
                return DtoUtil.returnFail("登录失败",ErrorCode.AUTH_AUTHENTICATION_FAILED);
            }else{
                //登录成功
                //生成token
                String token = tokenService.generateToken(request.getHeader("user-agent"),user);
                //保存token到redis PC-2H 移动端-无线时间
                if (!tokenService.saveToken(token,user)){
                    return DtoUtil.returnFail("redis异常",ErrorCode.AUTH_UNKNOWN);
                }
                //返回到客户端
                Date date = new SimpleDateFormat("yyyyMMddHHmmss")
                        .parse(token.split("-")[3]);
                ItripTokenVO itripTokenVO = new ItripTokenVO(token,
                        date.getTime()+TokenService.TOKEN_TIMEOUT,date.getTime());
                return DtoUtil.returnDataSuccess(itripTokenVO);
            }
        }catch (LoginException e){
            //未激活
            return DtoUtil.returnFail("账户未激活",ErrorCode.AUTH_NOT_ACTIVATED);
        }catch (DatabaseException e){
            //数据库异常
            return DtoUtil.returnFail("数据库异常",ErrorCode.AUTH_UNKNOWN);
        }catch (Exception e){
            e.printStackTrace();
            return DtoUtil.returnFail("生成Token异常",ErrorCode.AUTH_UNKNOWN);
        }

    }

    /**
     * 注销
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/logout",method = RequestMethod.GET,produces = "application/json")
    @ResponseBody
    public Dto logout(HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        if(tokenService.validateToken(token,agent)){
            //执行退出
            tokenService.deleteToken(token);
            return DtoUtil.returnSuccess();
        }else{
            return DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
        }
    }
}
